package simple.utils.data.serializers;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;

/**
 * Created by rehak on 5/7/14.
 */
public class JsonObjectSerializer implements Serializer {

    private final Class<?> cls;

    public JsonObjectSerializer(Class<?> cls) {
        this.cls = cls;
    }

    @Override
    public byte[] toBytes(Object o) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
        if (!mapper.canSerialize(o.getClass())) {
            throw new IOException("Unable to serialize class " + o.getClass());
        }
        return mapper.writeValueAsBytes(o);
    }

    @Override
    public Object fromBytes(byte[] data) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
        JavaType jt = mapper.constructType(cls);
        if (!mapper.canDeserialize(jt)) {
            throw new IOException("Unable to deserialize " + cls.getName());
        }
        return mapper.readValue(data,cls);
    }

}
